// 导入模块
import Vue from 'vue'
import VueRouter from "vue-router";
import { getToken } from '../utils/localData';
// 路由映射关系
import Login from "../views/Login.vue"
import Register from "../views/Register.vue"
import User from "../views/User.vue"
import UserEdit from "../views/UserEdit.vue"
import Home from "../views/Home.vue"
import Artcle from'../views/Artcle.vue'
import UserFollow from'../views/UserFollow.vue'
import UserComment from'../views/UserComment.vue'
import UserStar from '../views/UserStar.vue'
import Comment from '../views/Comment.vue'
import Category from '../views/Category.vue'
import Search from '../views/Search.vue'
Vue.use(VueRouter)
const routes =[

    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/user', component: User },
    { path: '/user_edit', component: UserEdit },
    { path:'/artcle/:id', component: Artcle},
    { path: '/', component: Home },
    { path:'/user_follow', component: UserFollow},
    { path:'/user_comment', component: UserComment},
    { path:'/user_star', component: UserStar},
    { path:'/comment/:id', component: Comment},
    { path:'/category', component: Category},
    { path:'/search', component: Search},
]
// new 一个路由实例
const router=new VueRouter({
    routes,
    mode:'history',
});
/* 
 路由守卫
   to     目标路由对象地址
   from   跳转前路由对象地址
   next   next是否放行
*/
router.beforeEach((to, from, next) => {
    const PathArr =['/user','/user_edit']
    // 部分页面访问的时候需要确认是否有 token
    if(PathArr.indexOf(to.path) !== -1) {
        // 如果有成功获取到 token
        if(getToken()){
            // 放行
            next()
        }else{
            // 没有 token 就跳转到登陆页
            next({path:'/login'})
        }
        // 普通页面，直接放行
    }else{
        next()
    }
    
})

// 导出路由实例
export default router